<template>
  <div class="sensitive-word-ranking">
    <el-card shadow="hover" class="chart-card">
      <template #header>
        <div class="card-header">
          <span>敏感词排行</span>
          <el-button type="primary" size="small" @click="loadSensitiveRanking">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
      </template>
      <div class="chart-container" id="sensitiveWordChart" v-loading="loading">
        <!-- Chart will be rendered here -->
      </div>
    </el-card>
    
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <span>敏感词详情</span>
          <el-input
            v-model="searchWord"
            placeholder="搜索敏感词"
            style="width: 200px"
            clearable
            @input="filterSensitiveWords"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <el-table
        :data="filteredSensitiveRankings"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column type="index" width="60" align="center"></el-table-column>
        <el-table-column prop="word" label="敏感词" show-overflow-tooltip>
          <template #default="scope">
            <span class="sensitive-word">{{ scope.row.word }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="出现次数" width="120" sortable></el-table-column>
        <el-table-column prop="lastDetected" label="最近检测时间" width="180"></el-table-column>
        <el-table-column prop="level" label="敏感级别" width="120">
          <template #default="scope">
            <el-tag :type="getSensitiveLevelTag(scope.row.level)">
              {{ getSensitiveLevelText(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh, Search } from '@element-plus/icons-vue';
import { getSensitiveRanking } from '../../api/admin';
// 引入echarts核心模块
import * as echarts from 'echarts';

const props = defineProps({});
const emit = defineEmits([]);

// 数据
const sensitiveRankings = ref([]);
const filteredSensitiveRankings = ref([]);
const loading = ref(false);
const searchWord = ref('');

// 图表实例
let sensitiveWordChart = null;

// 加载敏感词排行数据
const loadSensitiveRanking = async () => {
  loading.value = true;
  try {
    const response = await getSensitiveRanking(20); // 获取前20个敏感词
    if (response.code === 200) {
      // 处理API返回的数据
      sensitiveRankings.value = response.data.map(item => ({
        word: item.word,
        count: item.count,
        level: getLevelByCount(item.count), // 根据出现次数确定级别
        lastDetected: item.lastDetected || new Date().toISOString().slice(0, 19).replace('T', ' ')
      })) || [];
      
      filteredSensitiveRankings.value = [...sensitiveRankings.value];
      
      // 等待DOM更新后初始化图表
      nextTick(() => {
        renderSensitiveWordChart();
      });
    } else {
      ElMessage.error(response.message || '获取敏感词排行失败');
    }
  } catch (error) {
    console.error('获取敏感词排行失败:', error);
    ElMessage.error('获取敏感词排行失败: ' + (error.message || '未知错误'));
    sensitiveRankings.value = [];
    filteredSensitiveRankings.value = [];
  } finally {
    loading.value = false;
  }
};

// 根据出现次数确定敏感级别
const getLevelByCount = (count) => {
  if (count >= 10) {
    return 'high';
  } else if (count >= 5) {
    return 'medium';
  } else {
    return 'low';
  }
};

// 渲染敏感词排行图表
const renderSensitiveWordChart = () => {
  const chartDom = document.getElementById('sensitiveWordChart');
  if (!chartDom) return;
  
  // 销毁已有实例
  if (sensitiveWordChart) {
    sensitiveWordChart.dispose();
  }
  
  // 创建图表实例
  sensitiveWordChart = echarts.init(chartDom);
  
  // 准备图表数据 - 使用实际API数据
  const data = sensitiveRankings.value.slice(0, 10).map(item => ({
    name: item.word,
    value: item.count
  }));
  
  data.sort((a, b) => b.value - a.value);
  
  // 设置图表选项
  const option = {
    title: {
      text: '敏感词TOP10排行',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    series: [
      {
        name: '出现次数',
        type: 'bar',
        data: data.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#F56C6C' },
            { offset: 1, color: '#E6A23C' }
          ])
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        }
      }
    ]
  };
  
  // 渲染图表
  sensitiveWordChart.setOption(option);
  
  // 添加防抖处理窗口大小变化，提高性能
  window.addEventListener('resize', resizeChart);
};

// 防抖处理窗口大小变化
let resizeTimer = null;
const resizeChart = () => {
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  resizeTimer = setTimeout(() => {
    sensitiveWordChart && sensitiveWordChart.resize();
  }, 100);
};

// 敏感级别标签和文本
const getSensitiveLevelTag = (level) => {
  const levels = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info',
    'default': 'info'
  };
  return levels[level] || levels.default;
};

const getSensitiveLevelText = (level) => {
  const texts = {
    'high': '高',
    'medium': '中',
    'low': '低',
    'default': '未知'
  };
  return texts[level] || texts.default;
};

// 过滤敏感词
const filterSensitiveWords = () => {
  if (!searchWord.value) {
    filteredSensitiveRankings.value = [...sensitiveRankings.value];
    return;
  }
  
  filteredSensitiveRankings.value = sensitiveRankings.value.filter(item => 
    item.word.toLowerCase().includes(searchWord.value.toLowerCase())
  );
};

// 组件卸载前清理图表实例
onBeforeUnmount(() => {
  if (sensitiveWordChart) {
    sensitiveWordChart.dispose();
    sensitiveWordChart = null;
  }
  window.removeEventListener('resize', resizeChart);
});

// 初始化
onMounted(() => {
  loadSensitiveRanking();
});

// 暴露方法给父组件
defineExpose({
  loadSensitiveRanking
});
</script>

<style scoped>
.sensitive-word-ranking {
  width: 100%;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.sensitive-word {
  color: #F56C6C;
  font-weight: bold;
}

@media (max-width: 768px) {
  .chart-container {
    height: 300px;
  }
}
</style> 